const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let staff = await db.collection('staff').field({
		group_id: true,
	}).where({
		_openid: wxContext.OPENID,
		shop_id: event.shop_id,
	}).get()
	if (staff.data.length == 0) {
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	staff = staff.data[0]

	if (staff.group_id != 1) {
		//仅创始人可操作员工管理
		return {
			code: 20003,
			msg: '您无权进行此操作'
		}
	}
	var $ = db.command.aggregate
	var data
	await db.collection('staff').aggregate().lookup({
		from: 'user',
		localField: '_openid',
		foreignField: '_openid',
		as: 'user',
	}).match({
		shop_id: event.shop_id
	}).skip(event.skip).limit(15).sort({
		'create_time': -1
	}).replaceRoot({
		newRoot: $.mergeObjects([$.arrayElemAt(['$user', 0]), '$$ROOT'])
	}).project({
		_id: 1,
		group_id: 1,
		_openid: 1,
		nickName: 1,
		avatarUrl: 1
	}).end().then(res => {
		data = res.list
		console.log(res)
	}).catch(err => console.error(err))
	return {
		code: 200,
		data: data
	}

}